package com.wenhai.spring.dependency.lookup;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import java.util.Date;

/**
 * {@link ObjectProvider}
 *
 * @Author:wenhai
 * @Description: ObjectProvider
 * @Date:2020/3/7
 */
public class ObjectProviderDemo {
    @SuppressWarnings({"deprecated", "cast"})
    public static void main(String[] args) {
        Date date = new Date();
        int day = date.getDay();
        AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext();
        cxt.register(ObjectProviderDemo.class);
        cxt.refresh();
        lookupByObjectProvider(cxt);
        lookupIfAvailable(cxt);
        lookupByStreamOps(cxt);
        cxt.close();
    }

    private static void lookupByStreamOps(AnnotationConfigApplicationContext cxt) {
        ObjectProvider<String> beanProvider = cxt.getBeanProvider(String.class);
        beanProvider.stream().forEach(System.out::println);
    }

    private static void lookupIfAvailable(AnnotationConfigApplicationContext cxt) {
        ObjectProvider<User> userObjectProvider = cxt.getBeanProvider(User.class);
        User user = userObjectProvider.getIfAvailable(User::createUser);
        System.out.println("当前User" + user);

    }

    @Bean
    @Primary
    public String helloWorld() {
        return "Hello,World";
    }

    @Bean
    public String message() {
        return "Message";
    }

    private static void lookupByObjectProvider(AnnotationConfigApplicationContext cxt) {
        ObjectProvider<String> beanProvider = cxt.getBeanProvider(String.class);
        System.out.println(beanProvider.getObject());
    }



}
